package book_management.book;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 书架类,所有书籍在这个类中存储
 */
public class BookList {
    // 使用JDK内置的动态数组
    // 保存每个书籍对象
    private static List<Book> books = new ArrayList<>();
    // 保存所有的书籍名称，作为操作书籍的索引
    private static List<String> booksName = new ArrayList<>();
    // 静态代码块
    static {
        // 初始化操作
        books.add(new Book("水浒传","施耐庵",
                66.6,"武侠小说"));
        books.add(new Book("三国演义","罗贯中",
                88.6,"谋略小说"));
        books.add(new Book("西游记","吴承恩",
                99.6,"玄幻小说"));
        books.add(new Book("红楼梦","曹雪芹",
                260.6,"牛逼小说"));

        booksName.add("水浒传");
        booksName.add("三国演义");
        booksName.add("西游记");
        booksName.add("红楼梦");
    }

    /**
     * 根据书籍名称判断当前书架上是否存在该书
     * @param booksName
     * @return
     */
    public boolean isContains(String booksName) {
        // ArrayList.contains();
        if (this.booksName.contains(booksName)) {
            return true;
        }else {
            return false;
        }
    }

    public void bookUpdate(String booksName,double price,String type) {
        Book book = findBook(booksName);
        book.setPrice(price);
        book.setType(type);
    }

    public boolean isBookBorrowed(String booksName) {
        Book book = findBook(booksName);
        return book.isBorrowed();
    }

    public void addBook(Book book) {
        books.add(book);
        booksName.add(book.getName());
    }

    public void printBook() {
        // 遍历Books数组
        Iterator<Book> iterator = books.iterator();
        while (iterator.hasNext()) {
            Book book = iterator.next();
            System.out.println(book);
        }
    }

    public void borrowBook(String booksName) {
        // 需要根据书名 -》 具体的Book对象 -> 方法(private)
        Book book = findBook(booksName);
        book.setBorrowed(true);
    }

    public void returnBook(String booksName) {
        Book book = findBook(booksName);
        book.setBorrowed(false);
    }

    public void bookUndercarriage(String booksName) {
        Book book = findBook(booksName);
        books.remove(book);
        this.booksName.remove(booksName);
    }

    private Book findBook(String booksName) {
        // 需要迭代查找该书
        Iterator<Book> iterator = books.iterator();
        while (iterator.hasNext()) {
            Book book = iterator.next();
            if (book.getName().equals(booksName)) {
                return book;
            }
        }
        return null;
    }
}